package com.tduck.cloud.api.web.controller;


import com.tduck.cloud.common.util.Result;
import com.tduck.cloud.project.entity.ImageAttachmentEntity;
import com.tduck.cloud.project.mapper.ImageAttachmentMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 文件上传
 * @Author xyd
 **/
@Slf4j
@Api(tags = "文件上传接口")
@RestController
@RequestMapping("/picUpload")
public class PicUploadController {


    @Autowired
    private ImageAttachmentMapper imageAttachmentMapper;

    @Value("${picUploadBaseUrl}")
    private  String picUploadBaseUrl;



    //请求订单列表
    @ResponseBody
    @RequestMapping(value = "/batch/upload", method = RequestMethod.POST)
    public String getOrderDtl(@RequestParam(value = "file") MultipartFile files[], HttpServletRequest request) {
        String picUrls="";
        String uploadPath = picUploadBaseUrl;
        System.out.println("=====picUploadBaseUrl"+picUploadBaseUrl);
        System.out.println("=====uploadPath"+uploadPath);
        File uploadDirectory = new File(uploadPath);
        if (uploadDirectory.exists()) {
            if (!uploadDirectory.isDirectory()) {
                uploadDirectory.delete();
            }
        } else {
            uploadDirectory.mkdir();
        }
        //这里可以支持多文件上传
        if (files != null && files.length >= 1) {
            BufferedOutputStream bw = null;
            try {

                for (MultipartFile file : files) {
                    String fileName = file.getOriginalFilename();
                    //判断是否有文件且是否为图片文件
                    if(fileName!=null && !"".equalsIgnoreCase(fileName.trim()) && isImageFile(fileName)) {
                        String picBaseUrl="/car-manage-img/" + UUID.randomUUID().toString()+ getFileType(fileName);
                        String picUrl=uploadPath +picBaseUrl;
                        //创建输出文件对象
                        File outFile = new File(picUrl);
                        //拷贝文件到输出文件对象
                        FileUtils.copyInputStreamToFile(file.getInputStream(), outFile);
                        ImageAttachmentEntity t = new ImageAttachmentEntity();
                        t.setName(fileName);
                        t.setPath(picUrl);
                        t.setCreateTime(new Date());
                        t.setMediaType(file.getContentType());
                        t.setSize(file.getSize());
                        imageAttachmentMapper.insert(t);
                        picUrls+=picBaseUrl+",";
                    }
                }
            } catch (Exception e) {
                //e.printStackTrace();
                return "upload err";
            } finally {
                try {
                    if (bw != null) {
                        bw.close();
                    }
                } catch (IOException e) {
                    //e.printStackTrace();
                    return "upload err";
                }
            }
        }
        System.out.println("=====picUrls"+picUrls);
        picUrls = picUrls.substring(0, picUrls.length() - 1);
        System.out.println("=====picUrls"+picUrls);
        return picUrls;
    }

    @ResponseBody
    @RequestMapping(value = "/welink/upload", method = RequestMethod.POST)
    public Result shortOutlineAsr(@RequestParam(name = "file") MultipartFile voiceFile) {
        try {
            String uploadPath = picUploadBaseUrl;
            System.out.println("=====picUploadBaseUrl"+picUploadBaseUrl);

            //生成uuid
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //得到上传时的文件名
            String filename=voiceFile.getOriginalFilename();
            //上传目录地址
            //1.1保存到项目指定目录
            //String uploadDir="C:\\Users\\21112\\Documents\\我的资源\\idea\\shop\\src\\main\\resources\\static\\upload";
            //1.2 上传到相对路径 request.getSession().getServletContext().getRealPath("/")+"upload/";
            //1.2 此路径为tomcat下，可以输出看一看

            //如果目录不存在，自动创建文件夹
            File dir=new File(uploadPath);
            if(!dir.exists()){
                dir.mkdir();
            }

            String fileSuffix = filename.substring(filename.lastIndexOf("."));
            if(!fileSuffix.equalsIgnoreCase(".gif")
                    &&!fileSuffix.equalsIgnoreCase(".jpg")
                    &&!fileSuffix.equalsIgnoreCase(".jpeg")
                    &&!fileSuffix.equalsIgnoreCase(".bmp")
                    && !fileSuffix.equalsIgnoreCase(".png")
                    && !fileSuffix.equalsIgnoreCase(".webp")){
                log.info("文件格式不正确");
                return Result.failed("文件格式不正确");
            }

            String picBaseUrl="/car-manage-img/"+UUID.randomUUID().toString()+filename;
            String picUrl=uploadPath +picBaseUrl;
            //保存文件对象 加上uuid是为了防止文件重名
            File serverFile=new File(picUrl);
            voiceFile.transferTo(serverFile);
            return Result.success(picBaseUrl);

        } catch (Exception e) {
            //打印错误堆栈信息
            //e.printStackTrace();
            return Result.failed("上传失败");
        }
    }




    private Boolean isImageFile(String fileName) {
        String[] img_type = new String[]{".jpg", ".jpeg", ".png", ".gif", ".bmp"};
        if (fileName == null) {
            return false;
        }
        fileName = fileName.toLowerCase();
        for (String type : img_type) {
            if (fileName.endsWith(type)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件后缀名
     *
     * @param fileName
     * @return
     */
    private String getFileType(String fileName) {
        if (fileName != null && fileName.indexOf(".") >= 0) {
            return fileName.substring(fileName.lastIndexOf("."), fileName.length());
        }
        return "";
    }

}
